<?php


namespace App\severces;


use Elasticsearch\ClientBuilder;
use Illuminate\Support\Facades\Log;

class EsSeverce
{
    protected $client;

    /**
     * 链接es
     * EsSeverce constructor.
     */
    public function __construct()
    {
        $host = config('es.host');
        $client = ClientBuilder::create()->setHosts($host)->build();
        $this->client = $client;
    }

    /**
     *es添加
     * @param $indexNmae
     * @param array $body
     */
    public function esIndex($indexNmae,$body=[])
    {
        try {
            $params = [
                'index'=>$indexNmae,
                'id'=>$body['id'],
                'body'=>$body
            ];

            $res = $this->client->index($params);

            if($res){
                Log::info($body['id'] . '的房源同步数据成功');
            }
        }catch (\Exception $e){

                //写入es失败后处理
            Log::info($e->getMessage());
        }

    }

    /**
     * es搜索
     * @param $indexname 索引名称
     * @param $fangname  搜索内容
     * @return array|callable
     */
    public function esSearch($indexname,$fangname)
    {
        $params = [
            'index' => $indexname,
            'body'  => [
                'query' => [
                    'match' => [
                        'fang_name' => $fangname
                    ]
                ],

                'highlight'=>[
                    'pre_tags'=>['<span style="color: #ff0000;font-size: 20px">'],
                    'post_tags'=>['</span>'],
                    'fields'=>[
                        'fang_name'=>new \stdClass()
                    ]
                ]
            ]
        ];

        return $this->client->search($params);
    }
}
